//详情页模块
let express  = require("express");
let intercept = require('../tools/intercept');
let time = require('time-stamp');


let db = require('../tools/db');
let to = require('../tools/to');
let jwt = require('jsonwebtoken');
let {secret} = require('../tools/config');

let router = express.Router();


router.get('/detail',async (req,res)=>{
    let cid = req.query.cid;
    let sql1 = `SELECT
	A.id,
	A.tid,
	A.title,
	price,
	concat( '/uploads/course/', A.image_src ) AS image_src,
	A.type_name,
	A.area_name,
	A.grade_name,
	A.subject_name,
	A.category_name, 
	A.intro as courseIntro,
	B.intro as teacherIntro,
	B.realname,
	concat('/uploads/avatar/',B.head_photo_url) as head_photo_url
FROM
	e_course as A
	LEFT JOIN e_teacher as B ON A.tid = B.tid
	where A.cid=?`;
    let sql2 = `select id,cid,vnum,video_src,video_title from e_video where cid=?`;

    // let a = await db.query(sql1,[cid]);
    // let b = await db.query(sql2,[cid]);
    Promise.all([
        db.query(sql1,[cid]),
        db.query(sql2,[cid]),
    ]).then((data)=>{
        console.log(data);
        //将数据包装程前端想要的格式
        let obj = data[0][0];
        obj.video = data[1];
        res.json({code:200,data:obj,msg:"课程详情数据成功"})

    }).catch((err)=>{
        res.json({code:500,data:err,msg:"课程详情数据失败"})
    })
})

//token拦截验证中间件，需要验证的接口放在下面。不需要验证接口放他上方
router.use( intercept() );
//视频播放
router.get('/videoplay',async (req,res)=>{
    // console.log(req.headers);
    // let {token} = req.headers;
    let {id} = req.query;
    let sql = `select cid,vnum,concat('/uploads/video',video_src) as video_src,video_title from e_video where id=?`
    let a = await db.query(sql,[id]);
    res.json({code:200,data:a[0],msg:"视频数据成功"})
})

//课程报名
router.post('/study',async (req,res)=>{
    let {cid,mid} = req.body;
    if(!cid || !mid ){
        res.json({code:200,data:null,msg:"cid和mid不能为空"});
        return;
    }
    //检查该课程是否已经报名了 (如果mid代表的这个人已经报过该课程，就提示“不能重复报名”)

    let sql =  `insert into e_order(oid,cid,mid,createdate) values(?,?,?,?)`;
    let oid = time("YYYYMMDDHHmmssms");
    let a = await db.query(sql,[oid,cid,mid,Date.now()]);
    res.json({code:200,data:null,msg:"课程报名成功"})

})


module.exports = router;